package com.dangdang.service.impl;

import com.dangdang.dao.AddressDao;
import com.dangdang.entity.Address;
import com.dangdang.service.AddressService;
import com.dangdang.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class AddressServiceImpl implements AddressService {
    @Override
    public List<Address> selectAllAddr(int uid) {
        SqlSession sqlSession = null;
        List<Address> addresses = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            AddressDao dao = sqlSession.getMapper(AddressDao.class);
            addresses = dao.selectAllAddr(uid);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return addresses;
    }
    public void update(Address address){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            AddressDao dao = sqlSession.getMapper(AddressDao.class);
            dao.update(address);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }
    @Override
    public Address selectById(int id) {
        SqlSession sqlSession = null;
        Address address = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            AddressDao dao = sqlSession.getMapper(AddressDao.class);
            address = dao.selectById(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return address;
    }
    public void insert(Address address){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            AddressDao dao = sqlSession.getMapper(AddressDao.class);
            dao.insert(address);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }
}
